package com.zhjhserver.socket;

import java.nio.charset.Charset;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

import com.zhjhserver.utils.PackData;

public class ActionScriptEncoder extends ProtocolEncoderAdapter {
	public ActionScriptEncoder(Charset charset) {
	}

	@Override
	public void encode(IoSession session, Object message,
			ProtocolEncoderOutput out) throws Exception {

		PackData pkg = (PackData) message;
		if (pkg.limit() > 0) {
			IoBuffer buffer = pkg.getIoBuffer();
			IoBuffer outBuffer = null;
			int dataLength = buffer.limit() - buffer.remaining();
			if (dataLength == 0) {
				System.out.println("*****旧包转发*****");
				outBuffer = IoBuffer.allocate(buffer.limit()+PackData.DATA_TITLE);
				outBuffer.putInt(buffer.limit());
			} else {
				System.out.println("*****新包转发*****");
				if (buffer.position() > 0) {
					buffer.flip();
				}
				outBuffer = IoBuffer.allocate(dataLength
						+ PackData.DATA_TITLE);
				outBuffer.putInt(dataLength);
			}
			outBuffer.put(buffer);
			System.out.println("出包："+pkg);
			synchronized (out) {
				outBuffer.clear();
				out.write(outBuffer);
				out.flush();
			}

		} else {
			System.out.println("编码的包数据为空");
		}
	}
}
